// pages/post-detail/post-detail.js

import {postList} from "../../data/data.js"
const app = getApp()
// console.log(app)
Page({

  /**
   * 页面的初始数据
   */
  data: {
    _pid: null,
    collected: false,
    _postCollection: {},
    isPlay: false,
    _start: null
  },

  onShare(){
    wx.showActionSheet({
      itemList: ['分享到QQ','分享到微信'],
    })
  },

  onMusicStart(){
    this.data._start.src = postList[this.data._pid].music.url
    this.data._start.title = postList[this.data._pid].music.title
    this.setData({
      isPlay:true
    })
    app.gIsMusic = this.data.isPlay
    app.gIsMusicId = this.data._pid
    // console.log(app.gIsMusicId)
  },
  onMusicStop(){
    this.data._start.pause()
    this.setData({
    isPlay:false  
    })
    app.gIsMusic = this.data.isPlay
    app.gIsMusicId = this.data._pid
  },
  onMusicEnd(){
    this.setData({
      isPlay:false  
      })
    app.gIsMusic = this.data.isPlay
  },

  currentMusic(){
    if(app.gIsMusic && app.gIsMusicId === this.data._pid){
      return true
    }
    return false
    console.log(this.currentMusic)
  },

  onCollection(){
    const postCollection = this.data._postCollection
    postCollection[this.data._pid]= !this.data.collected
    wx.setStorageSync('hide', postCollection)
    this.setData({
      collected: !this.data.collected
    })
    wx.showToast({
      title: this.data.collected?'收藏成功': '取消收藏',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    const postData = postList[options.pid]
    this.data._pid = options.pid
    const postCollection = wx.getStorageSync('hide')
    this.data._postCollection = postCollection
    const collected = this.data._postCollection[this.data._pid]
    const start = wx.getBackgroundAudioManager()
    this.data._start = start
    this.setData({
      postData,
      collected,
      isPlay:this.currentMusic()
    })
    start.onPlay(this.onMusicStart)
    start.onPause(this.onMusicStop)
    start.onEnded(this.onMusicEnd)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})